package com.qifan.energy.http.request;

import com.qifan.energy.global.Constant;
import com.orhanobut.logger.Logger;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/*
* 参考链接：
* https://blog.csdn.net/qq_36707431/article/details/77680252
* https://blog.csdn.net/li18518326892/article/details/86640881?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase
* */
public class BaseUrlInterceptor implements Interceptor {

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        //获取request
        Request request = chain.request();
        //从request中获取原有的HttpUrl实例oldHttpUrl
        HttpUrl oldHttpUrl = request.url();
        //获取request的创建者builder
        Request.Builder builder = request.newBuilder();
        //从request中获取headers，通过给定的键url_name
        List<String> headerValues = request.headers(Constant.BASEURL_KEY);
        if (headerValues != null && headerValues.size() > 0) {
            //如果有这个header，先将配置的header删除，因此header仅用作app和okhttp之间使用
            builder.removeHeader(Constant.BASEURL_KEY);
            //匹配获得新的BaseUrl
            String headerValue = headerValues.get(0);
            HttpUrl newBaseUrl = null;
            if (Constant.PORT_KEY_8085.equals(headerValue)) {
                newBaseUrl = HttpUrl.parse(Constant.BaseUrl8085);
            } else if (Constant.PORT_KEY_8081.equals(headerValue)) {
                newBaseUrl = HttpUrl.parse(Constant.BaseUrl8081);
            } else if (Constant.PORT_KEY_8080.equals(headerValue)) {
                newBaseUrl = HttpUrl.parse(Constant.BaseUrl8080);
            } else{
                newBaseUrl = oldHttpUrl;
            }
            //重建新的HttpUrl，修改需要修改的url部分
            HttpUrl newFullUrl = oldHttpUrl
                    .newBuilder()
                    /*.scheme("https")//更换网络协议*/
                    .host(newBaseUrl.host())//更换主机名
                    .port(newBaseUrl.port())//更换端口
                    /*.removePathSegment(0)//移除第一个参数*/
                    .build();
            //重建这个request，通过builder.url(newFullUrl).build()；
            // 然后返回一个response至此结束修改
            Logger.e("打印URL", "intercept: "+newFullUrl.toString());
            return chain.proceed(builder.url(newFullUrl).build());
        }
        return chain.proceed(request);
    }
}
